package com.xxx.shetuan3.service.impl;

import com.xxx.shetuan3.dao.UserDao;
import com.xxx.shetuan3.exception.ApiException;

import com.xxx.shetuan3.pojo.User;
import com.xxx.shetuan3.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User findUserByUserId(Integer userId) {
        User user =  userDao.findUserByUserId(userId);
        if(user==null){
            throw new ApiException("用户不存在");
        }else{
            return user;
        }
    }

    @Override
    public boolean saveUser(User user) {
        return userDao.saveUser(user);
    }

    @Override
    public User findUserByAccount(String account) {
        return userDao.findUserByAccount(account);
    }

    @Override
    public boolean updateUser(User user) {
        String password = user.getPassword();
        password = passwordEncoder.encode(password);
        user.setPassword(password);
        return userDao.updateUser(user);
    }

    @Override
    public boolean deleteUserById(int user_id) {
        return userDao.deleteUserById(user_id);
    }

    @Override
    public boolean regist(User user) {
        String account = user.getAccount();
        if(user.getPassword()==null){
            throw new ApiException("密码不能为空");
        }else if(user.getAccount()==null){
            throw new ApiException("账号不能为空");
        }else if(user.getName()==null){
            throw new ApiException("姓名不能为空");
        }else if(userDao.findUserByAccount(account)!=null){
            throw new ApiException("账号已存在");
        }
        user.setRole("student");
        String password = passwordEncoder.encode(user.getPassword());
        user.setPassword(password);
        userDao.saveUser(user);
        return true;
    }
}
